using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

namespace Helpers
{
    public static class FullTextHelper
    {
        public static string GetFullTextSearchParam(string keywords)
        {
            keywords = System.Text.RegularExpressions.Regex.Replace(keywords, "[^a-zA-Z0-9*? ]", " ");
            keywords = System.Text.RegularExpressions.Regex.Replace(keywords, @"\*{2,}", "*");
            keywords = System.Text.RegularExpressions.Regex.Replace(keywords, @"\?{2,}", "?");

            StringBuilder sb = new StringBuilder();
            if (!String.IsNullOrEmpty(keywords))
            {
                keywords = keywords.Trim();
                if (keywords.Length > 100)
                {
                    keywords = keywords.Substring(0, 100);
                }

                string[] keywordArray = keywords.Split(' ');
                for (int i = 0; i <= keywordArray.Length - 1; i++)
                {
                    string s = keywordArray[i].Trim();
                    string sUpperCase = s.ToUpper();
                    if (s.Length >= 2)
                    {
                        if (sUpperCase.Equals("OR") || sUpperCase.Equals("AND"))
                        {
                            if ((i != 0) && (i != keywordArray.Length - 1))
                            {
                                string prevString = keywordArray[i - 1].Trim().ToUpper();
                                if (!(prevString.Equals("OR") || prevString.Equals("AND")))
                                {
                                    sb.AppendFormat("{0} ", sUpperCase);
                                }
                            }
                        }
                        else
                        {
                            sb.AppendFormat("\"{0}\" ", s);
                        }
                    }
                }
            }
            keywords = sb.ToString();
            keywords = keywords.Replace("\" \"", " ");
            return keywords;
        }
    }
}